package org.aplikator.client.widgets;

import org.aplikator.client.Aplikator;
import org.aplikator.client.data.ClientContext;
import org.aplikator.client.data.Record;
import org.aplikator.client.descriptor.FunctionDTO;
import org.aplikator.client.rpc.Callback;
import org.aplikator.client.rpc.impl.RunFunction;
import org.aplikator.client.rpc.impl.RunFunctionResponse;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;

public class FunctionButtonWidget extends Button {
    private final FunctionDTO function;
    private FormWidget containingForm;

    public FunctionButtonWidget(FunctionDTO function, FormWidget containingForm) {
        this.function = function;
        this.containingForm = containingForm;
        containingForm.registerFunctionButton(this);
        this.setText(function.getLocalizedName());
        this.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                Record functionParameters = null;// TODO functionParameters
                                                    // from function descriptor
                                                    // and wizard
                ClientContext clientContext = Aplikator.clientContext.clone();
                clientContext.setCurrentRecord(FunctionButtonWidget.this.containingForm.getOriginal());// TODO
                                                                                                       // handle
                                                                                                       // dirty
                                                                                                       // form
                Aplikator.aplikatorService.execute(new RunFunction(FunctionButtonWidget.this.function, clientContext, functionParameters), new Callback<RunFunctionResponse>() {
                    public void process(RunFunctionResponse response) {
                        Window.alert(response.getResponse()); // TODO better
                                                              // response
                    }
                });
                Window.alert("Function "+FunctionButtonWidget.this.function.getLocalizedName() + " started."); //TODO correct localization
            }
        });
    }

}
